<template>
  <basic-container>
    <avue-crud
      :option="option"
      :data="data"
      ref="crud"
      v-model="form"
      :table-loading="loading"
      @selection-change="selectionChange"
      :permission="permissionList"
      :page="page"
      @refresh-change="refreshChange"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
	  :cell-style="cellStyle"
      @on-load="onLoad"
    >
      <template slot="display" slot-scope="scope">
        <i class="el-icon-circle-check" style="font-size:24px" v-if="scope.row.display"></i>
        <i class="el-icon-circle-close" style="font-size:24px" v-else></i>
      </template>
      <template slot-scope="scope" slot="menuLeft">
        <el-button
          type="primary"
          size="small"
          @click.stop="handleAdd(null)"
        >新增分类</el-button>
      </template>
      <template slot="menu" slot-scope="scope">
        <el-button
          :size="scope.size"
          :type="scope.type"
          icon="el-icon-plus"
          v-if="scope.row.level==0"
          @click.stop="handleAdd(scope.row)"
        >新增</el-button>
        <el-button
          :size="scope.size"
          :type="scope.type"
          icon="el-icon-edit"
          @click.stop="handleEdit(scope.row)"
        >编辑</el-button>
        <el-button
          :size="scope.size"
          :type="scope.type"
          icon=" el-icon-delete"
          @click.stop="rowDel(scope.row)"
        >删除</el-button>
      </template>
    </avue-crud>
    <el-dialog
      width="60%"
      :visible.sync="dialogFormVisible"
      :title="title"
      @close="closeDialog"
      append-to-body
      :close-on-click-modal="false"
    >
      <avue-form ref="form" v-model="obj" :option="optionAdd" @submit="submit"></avue-form>
<!--      <div slot="footer" class="dialog-footer" style="margin-top: -2rem;">-->
<!--        <el-button type="primary" v-if="isAdd" @click="submit" :loading="addbtnLoading">提交</el-button>-->
<!--        <el-button type="primary" v-else @click="upDataSubmit" :loading="editbtnLoading">确定</el-button>-->
<!--        <el-button @click="closeDialog">取消</el-button>-->
<!--      </div>-->
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  remove,
  update,
  add
} from "@/api/base/goods/seller/goodsClass";
import {
  testSort,
  testAccountName
} from '@/util/util';
import { mapGetters } from "vuex";

export default {
  data() {
    return {
      form: {},
      query: {},
      isAdd:true,
      loading: true,
      rolesTree: [],
      rolesKeys: [],
      box: false,
      dialogFormVisible: false,
      pageTotal: false,
      // isAdd: true,
      title: "",
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      deleteList: [],
      obj: {},
      optionAdd: {
        labelWidth: 150,
        emptyBtn:false,
        column: [
          {
            label: "分类名称",
            prop: "className",
            row: true,
            span: 18,
            maxlength: 12,
            showWordLimit: true,
            rules: [
              {
                required: true,
                message: "请输入分类名称",
                trigger: "blur"
              },
			  {
				validator:testAccountName,
                trigger: "blur"
			  }
            ]
          },
          {
            label: "分类排序",
            prop: "sequence",
            row: true,
            minRows: 0,
            maxlength: 5,
            span: 18,
            rules: [
              {
                required: true,
                message: "请输入分类排序",
                trigger: "blur"
              },
              {
                validator: testSort,
                trigger: "blur"
              }
            ]
          },
          {
            label: "显示状态",
            prop: "display",
            type: "radio",
            span: 18,
            dicData: [
              {
                label: "是",
                value: true
              },
              {
                label: "否",
                value: false
              }
            ],
            rules: [
              {
                required: true,
                message: "请选择显示状态",
                trigger: "click"
              }
            ]
          }
        ]
      },
      option: {
        // selection: true,
        headerAlign: "center",
        align: "center",
        border: true,
        defaultExpandAll: false,
        menu: true,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        viewBtn: false,
        column: [
          {
            label: "分类名称",
            prop: "className",
            align: "left",
          },
          {
            label: "排序",
            prop: "sequence"
          },
          {
            label: "显示",
            prop: "display",
            slot: true
          }
        ]
      },
      data: [
        {
          id: 1,
          event: "事件1",
          icon: "el-icon-circle-check",
          children: [
            {
              id: 2,
              event: "事件2",
              icon: "el-icon-error"
            },
            {
              id: 2,
              event: "事件2",
              icon: "el-icon-circle-close"
            }
          ]
        }
      ]
    };
  },
  watch:{
    dialogFormVisible(val){
      if(!val){
        this.$nextTick(()=>{
          this.$refs["form"].clearValidate();
        });
      }
    },
    pageTotal(val){
      if (val) {
        //针对删除数据用的所以this.page.total需要减一
        this.page.total -= 1;
        //当页面总条数 = （当前页数-1）*当前页条数，currentPage减1，重新获取列表
        if (this.page.total == (this.page.currentPage - 1) * this.page.pageSize && this.page.total - 1 != 0) {
          this.page.currentPage -= 1;
          //获取列表数据
          this.onLoad(this.page);
        } else {
          //获取列表数据
          this.onLoad(this.page);
        }
      }
    }
  },
  computed: {
    ...mapGetters(["permission", "userInfo"]),
    permissionList() {
      return {

      };
    }
  },
  methods: {
    closeDialog() {
      this.obj = {};
      this.dialogFormVisible = false;
    },
    //提交时再次效验表单
    // validateForm() {
    //   let flag = false;
    //   this.$refs.form.validate((valid) => {
    //     if (valid) {
    //       setTimeout(()=>{
    //         flag = true;
    //       },1000)
    //     }
    //   });
    //   console.log(flag)
    //   return flag;
    // },
    //新增提交
    submit(a, b) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.isAdd) {
            this.loading = true;
            add(this.obj).then(
                    (res) => {
                      if (res.data.code == 200) {
                        this.loading = false;
                        this.dialogFormVisible = false;
                        this.onLoad(this.page);
                        this.$nextTick(() => {
                          this.$refs["form"].clearValidate()
                        })
                        this.$message({
                          type: "success",
                          message: "新增成功!"
                        });
                        this.obj = {};
                        setTimeout(()=>{
                          b();
                        },1000)
                      }
                    },
                    error => {
                      this.$message({
                        type: 'error',
                        message: error
                      })
                    }
            );
          } else {
            //父属性新增子属性
            update(this.obj).then(
                    (res) => {
                      if (res.data.code == 200) {
                        this.loading = false;
                        this.dialogFormVisible = false;
                        this.onLoad(this.page);
                        this.$message({
                          type: "success",
                          message: "修改成功!"
                        });
                        this.obj = {};
                        setTimeout(()=>{
                          b();
                        },1000)
                      }
                    },
                    error => {
                      this.$message({
                        type: "error",
                        message: error
                      });
                    }
            )
          }
        }
      });
    },

    //多选
    selectionChange(list) {
      this.deleteList = [];
      for (let item of list) {
        this.deleteList.push(item.id);
      }
    },
    //新增分类
    handleAdd(row) {
      this.isAdd = true;
      Object.keys(this.obj).forEach(key => (this.obj[key] = ""));
      this.title = "新增分类";
      if (row != null) {
        this.obj.level = 1;
        this.obj.parentId = row.id;
      } else {
        this.obj.parentId = "";
        this.obj.level = 0;
      }
      this.obj.display = true;
      this.dialogFormVisible = true;
    },
    //编辑分类
    handleEdit(row) {
      this.isAdd = false;
      this.title = "编辑分类";
      this.obj = row;
      this.dialogFormVisible = true;
    },
    //单行删除
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(res => {
          if (res.data.code == 200) {
            this.pageTotal = true;
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          } else {
            this.$message.error(res.data.message);
          }
        });
    },
	cellStyle({row,columnIndex}){
		if(columnIndex==0){
			if(row.level==0){
				return {
					// color:'red',
					fontWeight:'bold',
				}
			}else if(row.level==1) {
              return {
                fontSize: '14px',
              }
            }else if(row.level==2) {
              return {
                fontSize: '13px',
                color:'#8a8c8d',
              }
            }else {
              return {
                fontSize: '12px',
                color:'#ccc',
              }
            }
		}
	},
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params,done) {
      this.page.currentPage=1
      this.query = params;
      this.onLoad(this.page, params,done);
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page);
    },
    onLoad(page, params = {},done) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        if(done){
          done();
        }
        this.loading = false;
        const data = res.data;
        this.page.total = data.count;
        this.data = data.data;
      });
      this.pageTotal = false;
    }
  }
};
</script>

<style>
</style>
